﻿@page
<div class="container">
    <div class="row p-1">
        <div class="col-1">Message</div>
        <div class="col-5"><input type="text" class="w-100" id="messageInput" /></div>
    </div>
    <div class="row p-1">
        <div class="col-6 text-end">
            <input type="button" id="sendButton" value="Send Message" />
        </div>
    </div>
    <div class="row p-1">
        <div class="col-6">
            <hr />
        </div>
    </div>
    <div class="row p-1">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>
</div>
<script>
    function addMessage(content) {
        var li = document.createElement("li");
        document.getElementById("messagesList").appendChild(li);
        li.textContent = content;
    }
    async function connect(hubName) {
        let res = await fetch('/negotiate/' + hubName)
        let data = await res.json();
        return new WebSocket(data.url, 'json.webpubsub.azure.v1');
    }
    (async function () {
        //Disable the send button until connection is established.
        document.getElementById("sendButton").disabled = true;
        // chat connection for the clients to talk to each other
        let chatConnection = await connect("chat");
        chatConnection.onopen = () => {
            document.getElementById("sendButton").disabled = false;
            chatConnection.send(JSON.stringify({
                type: 'joinGroup',
                group: 'group1'
            }));
            addMessage("connected to chat hub");
        };
        let output = document.querySelector('#output');
        chatConnection.onmessage = event => {
            let message = JSON.parse(event.data);
            if (message.type === 'message' && message.group === 'group1') {
                addMessage(message.data);
            }
        };
        document.getElementById("sendButton").addEventListener("click", function (event) {
            var message = document.getElementById("messageInput").value;
            chatConnection.send(JSON.stringify({
                type: 'sendToGroup',
                group: 'group1',
                data: message,
                dataType: "text"
            }));
            event.preventDefault();
        });
        // notification hub to receive data from the server
        let notificationConnection = await connect("notification");
        notificationConnection.onopen = () => {
            addMessage("connected to notification hub");
        };
        notificationConnection.onmessage = event => {
            let message = JSON.parse(event.data);
            if (message.type === 'message') {
                addMessage("Notification:" + message.data);
            }
        };
    })();
</script>
